package com.huluspace.learnhub.controller;

import com.huluspace.learnhub.dto.*;
import com.huluspace.learnhub.model.User;
import com.huluspace.learnhub.security.JwtUtil;
import com.huluspace.learnhub.service.JwtAuthService;
import com.huluspace.learnhub.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

  // 注入
  private final UserService userService;
  private final JwtAuthService jwtAuthService;
  private final JwtUtil jwtUtil;
  public AuthController(UserService userService, JwtAuthService jwtAuthService, JwtUtil jwtUtil) {
    this.userService = userService;
    this.jwtAuthService = jwtAuthService;
    this.jwtUtil = jwtUtil;
  }

  // 用户注册
  @PostMapping("/register")
  public ApiResponse<String> register(@RequestBody UserRegisterDTO dto) {
    try{
      userService.register(dto);
    }catch(RuntimeException e){
      return ApiResponse.error(e.getMessage());
    }
    return ApiResponse.success("注册成功");
  }

  // 用户登录
  @PostMapping("/login")
  public ApiResponse<UserStatusDTO> login(@RequestBody LoginRequest request) {
    UserStatusDTO response = userService.login(request.username, request.password);
    return ApiResponse.success(response);
  }

  // 退出或下线
  @PostMapping("/logout")
  public ApiResponse<String> logout(HttpServletRequest request) {
    String token = jwtUtil.extractToken(request);
    jwtAuthService.invalidateToken(token);
    return ApiResponse.success("已退出登录");
  }

  @GetMapping("/status")
  public ApiResponse<UserStatusDTO> getUserInfo(HttpServletRequest request) {
    String token = jwtUtil.extractToken(request);
    if (jwtAuthService.isTokenInvalid(token)) { // 判断token是否失效
      return ApiResponse.error("用户未登录");
    }
    String username = jwtUtil.extractUserName(token);
    Optional<User> user = userService.findByUsername(username);
    if (user.isEmpty()) {
      return ApiResponse.error("用户不存在");
    }
    UserStatusDTO userStatusDTO = new UserStatusDTO();
    userStatusDTO.setUsername(username);
    userStatusDTO.setToken(token);
    userStatusDTO.setRoles(user.get().roleNames());
    return ApiResponse.success(userStatusDTO);
  }

}

